using System;
using System.Linq;
using QAssetBundle;
using UnityEngine;
using QFramework;
using Random = UnityEngine.Random;

namespace ProjectSurvivor
{
	public partial class SimpleKnife : ViewController
	{
		
		
		private float mCurrentSeconds = 0f;

		private void Update()
		{
			mCurrentSeconds += Time.deltaTime;

			if (mCurrentSeconds >= Global.SimpleKnifeDuration.Value)
			{
				int damageTimes = Global.SuperSimpleKnife.Value ? Random.Range(2, 4) : 1;
				
				var enemies = FindObjectsByType<Enemy>(FindObjectsInactive.Exclude, FindObjectsSortMode.None)
					.OrderBy(enemy => Player.Default.Direction2DFrom(enemy).magnitude)
					.Take(Global.SimpleKnifeCount.Value + Global.AdditionFlyingCount.Value);

				int num = 0;
				foreach (var enemy in enemies)
				{
					if (num < 4)
					{
						ActionKit.DelayFrame(num * 11, () => AudioKit.PlaySound(Sfx.KNIFE))
							.StartGlobal();
						num++;
					}
					
					if (enemy)
					{
						Knife.Instantiate()
							.Show()
							.Position(this.Position())
							.Self(self =>
							{
								var rigidbody2D = self.GetComponent<Rigidbody2D>();
								var direction = enemy.NormalizedDirection2DFrom(Player.Default);
								self.transform.up = direction;
								rigidbody2D.velocity = direction * 10;

								var selfCache = self;
								int attackCount = 0;
								// 碰到敌人
								selfCache.OnTriggerEnter2DEvent(collider =>
								{
									var hurtbox = collider.GetComponent<HitHurtBox>();
									if (hurtbox && hurtbox.Owner.CompareTag("Enemy"))
									{
										attackCount++;
										DamageSystem.CalculateDamage(Global.SimpleKnifeDamage.Value * damageTimes, hurtbox.Owner.GetComponent<IEnemy>());

										if (attackCount >= Global.SimpleKnifeAttackCount.Value)
										{
											selfCache.DestroyGameObjGracefully();
										}
									}
								}).UnRegisterWhenGameObjectDestroyed(selfCache);
							
								// 超出一定范围销毁自己
								ActionKit.OnUpdate.Register(() =>
								{
									if (Player.Default)
									{
										if ((Player.Default.Position() - selfCache.Position()).magnitude > 20)
										{
											selfCache.DestroyGameObjGracefully();
										}
									}
								}).UnRegisterWhenGameObjectDestroyed(selfCache);
							});
					}
				}
				
				mCurrentSeconds = 0f;
			}
		}
	}
}
